package com.bigdata.schaduler.service;

import com.bigdata.schaduler.client.DolphinClient;
import com.bigdata.schaduler.domain.ScheduleDefineParam;
import org.apache.dolphinscheduler.common.enums.HttpMethod;
import org.apache.dolphinscheduler.dao.entity.Schedule;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import com.bigdata.schaduler.util.PageInfo;

import java.util.Optional;

public class SchedulerService {
  private final DolphinClient dolphinClient;

  public SchedulerService(DolphinClient dolphinClient) {
    this.dolphinClient = dolphinClient;
  }

  public String getSchedulerUri(Long projectCode) {
    return "projects/" + projectCode + "/schedules";
  }

  public Schedule create(Long projectCode, ScheduleDefineParam scheduleDefineParam) {
    String uri = getSchedulerUri(projectCode);
    return dolphinClient.requestFormData(HttpMethod.POST, uri, scheduleDefineParam, Schedule.class);
  }

  public void update(Long projectCode, Long scheduleId, ScheduleDefineParam scheduleDefineParam) {
    String uri = getSchedulerUri(projectCode) + "/" + scheduleId;
    dolphinClient.requestFormData(HttpMethod.PUT, uri, scheduleDefineParam, void.class);
  }

  public void update(Long projectCode, Long scheduleId, Schedule schedule) {
    ScheduleDefineParam scheduleDefineParam = new ScheduleDefineParam();
    scheduleDefineParam.converterToScheduleDefineParam(schedule);
    update(projectCode, scheduleId, scheduleDefineParam);
  }

  public PageInfo<Schedule> selectPageList(Long projectCode, Long processDefinitionCode, Integer pageNo, Integer pageSize) {
    pageNo = Optional.ofNullable(pageNo).orElse(1);
    pageSize = Optional.ofNullable(pageSize).orElse(10);

    String uri = getSchedulerUri(projectCode);
    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("pageNo", pageNo);
    params.add("pageSize", pageSize);
    params.add("processDefinitionCode", String.valueOf(processDefinitionCode));
    return dolphinClient.requestFormData(HttpMethod.GET, uri, params, PageInfo.class);
  }

  public void online(Long projectCode, Long scheduleId) {
    String uri = getSchedulerUri(projectCode) + "/" + scheduleId + "/online";
    dolphinClient.requestFormData(HttpMethod.POST, uri, null, Void.class);
  }

  public void offline(Long projectCode, Long scheduleId) {
    String uri = getSchedulerUri(projectCode) + "/" + scheduleId + "/offline";
    dolphinClient.requestFormData(HttpMethod.POST, uri, null, Void.class);
  }

  public void delete(Long projectCode, Long scheduleId) {
    String uri = getSchedulerUri(projectCode) + "/" + scheduleId;
    dolphinClient.requestFormData(HttpMethod.DELETE, uri, null, Void.class);
  }
}
